package com.epro.dx.util;

import android.content.Context;

import com.epro.dx.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * 时间格式化工具类
 * @author Zenglw
 * @version [1.0]
 * @date 2017-6-21
 *
 */
public class TimeFormat {
    /**
     * @param createAt
     * @return
     * @创建：Tony 2016-5-6下午4:53:16
     * @描述：根据本地时区格式化显示发信时间
     */
    public static CharSequence formatTimeToLocal(Context context, String createAt) {
        SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone pst = TimeZone.getTimeZone("Etc/GMT+0");
        try {
            localDateFormat.setTimeZone(pst);
            Date oldDate = localDateFormat.parse(createAt);
            localDateFormat.setTimeZone(TimeZone.getDefault());
            String oldDateText = localDateFormat.format(oldDate);
            Date newDate = new Date(System.currentTimeMillis());
            String newDateText = localDateFormat.format(newDate);
            String[] splitOldDate = oldDateText.split(" ");
            String[] splitNewDate = newDateText.split(" ");
            if ((splitNewDate[0]).equals(splitOldDate[0])) {
                //今天的消息，显示时间
                String[] timeSplit = splitOldDate[1].split(":");
                return timeSplit[0] + ":" + timeSplit[1];
            } else {
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(newDate);
                calendar.add(Calendar.DATE, -1);//把日期往前减一天.整数往后推,负数往前移动
                String yesterday = localDateFormat.format(calendar.getTime());//昨天的日期
                yesterday = yesterday.split(" ")[0];
                if (yesterday.equals(splitOldDate[0])) {
                    return context.getResources().getString(R.string.yesterday);
                } else {
                    return splitOldDate[0];

                }
            }
        } catch (ParseException e) {
            return null;
        }
    }
}
